<template>
  <div class="container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <!--suppress TypeScriptValidateTypes -->
          <el-button type="primary" :icon="Plus" @click="addItem">添加</el-button>
        </div>
      </template>
      <el-table :data="state.trademarkList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="tmName" label="品牌名" />
        <el-table-column prop="logoUrl" label="品牌Logo">
          <template #default="{ row }">
            <img :src="row.logoUrl" alt="" class="logoUrl" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <!--suppress TypeScriptValidateTypes -->
            <el-button type="warning" :icon="Edit" size="small" @click="editItem(row.id)"
              >修改</el-button
            >
            <!--suppress TypeScriptValidateTypes -->
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="delItem(row.id, row.tmName)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="state.current"
        :page-size="state.pageSize"
        :page-sizes="[3, 5, 7, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      v-model="showDialog"
      :title="!isEdit ? '新增' : '编辑弹框'"
      width="50%"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="dialogClose"
    >
      <el-form label-width="90px" :rules="rules" :model="formData" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" @click="confirmUpload">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import {
  addTrademark,
  delTrademark,
  detailTrademark,
  reqTrademarkList,
  updateTrademark
} from '@/api/trademark'
import { onMounted, reactive, ref } from 'vue'
import type { TrademarkItem } from '@/api/types'
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

const uploadUrl = import.meta.env.VITE_API_URL + '/admin/product/upload'
const showDialog = ref(false)
const formData = ref<TrademarkItem>({
  logoUrl: '',
  tmName: ''
})

const formRef = ref()
const isEdit = ref(false)
// 表单验证规则
const rules = reactive({
  tmName: [{ required: true, message: '品牌名不能为空', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '请上传品牌logo', trigger: 'change' }]
})

const delItem = (id: number, name: string) => {
  ElMessageBox.confirm(`确定删除${name}吗?`, 'danger', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await delTrademark(id)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        getTrademarkList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 确定上传
const confirmUpload = async () => {
  await formRef.value.validate()
  const res = isEdit.value
    ? await updateTrademark(formData.value)
    : await addTrademark(formData.value)
  if (res.code === 200) {
    ElMessage.success(isEdit.value ? '修改成功!' : '添加成功!')
    getTrademarkList()
    cancelUpload()
  }
}
const cancelUpload = () => {
  showDialog.value = false
  formRef.value.resetFields()
}

const addItem = () => {
  showDialog.value = true
  isEdit.value = false
}

const editItem = async (id: string) => {
  const res = await detailTrademark(id)
  if (res.code === 200) {
    formData.value = res.data
    showDialog.value = true
    isEdit.value = true
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  formData.value.logoUrl = response.data
  formRef.value?.validateField('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式必须是 jpeg 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图片体积不能大于 2MB!')
    return false
  }
  return true
}

const dialogClose = () => {
  cancelUpload()
}

const state = reactive({
  current: 1,
  pageSize: 5,
  total: 100,
  trademarkList: [] as TrademarkItem[]
})

onMounted(() => {
  getTrademarkList()
})

const handleSizeChange = (size: number) => {
  state.pageSize = size
  getTrademarkList()
}

const handleCurrentChange = (page: number) => {
  state.current = page
  getTrademarkList()
}

const getTrademarkList = async () => {
  const res = await reqTrademarkList(state.current, state.pageSize)
  if (res.code === 200) {
    state.total = res.data.total
    state.trademarkList = res.data.records
  }
}
</script>
<script lang="ts">
export default {
  name: 'TradeMark'
}
</script>

<style scoped lang="scss">
.container {
  margin-top: 20px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.logoUrl {
  width: 100px;
}

.avatar-uploader .avatar {
  width: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
